package pl.grabar.clinic.client.web.actions.reception.visit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import pl.grabar.clinic.core.dao.Dao;
import pl.grabar.clinic.core.domain.visit.Visit;
import pl.grabar.clinic.core.domain.visit.VisitSchedule;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Action("delete")
@InterceptorRef("grabarStack")
@Results({ @Result(name = "success", type = "redirectAction", location = "list"), @Result(name = "input", type = "redirectAction", location = "list") })
public class DeleteVisitAction extends ActionSupport implements Preparable {

	private static final long serialVersionUID = -3463650806594894620L;

	private static final Log LOG = LogFactory.getLog(DeleteVisitAction.class);

	@Autowired
	private Dao<VisitSchedule> visitScheduleDao;
	
	@Autowired
	private Dao<Visit> visitDao;

	private VisitSchedule visitSchedule;

	private String visitId;
	
	private Visit existingVisit;

	@Override
	public void prepare() throws Exception {
		visitSchedule = visitScheduleDao.findById(visitId);
		existingVisit = visitDao.findById(""+visitSchedule.getVisit());
	}

	@Override
	public void validate() {
		if (!hasErrors()) {
			if (visitSchedule == null) {
				addActionError(getText("pl.grabar.clinic.client.web.reception.visit.actions.no-such-visit"));
				LOG.error("Blad walidacji w trakcie usuwania wizyty. Wizyta o podanym id nie istnieje: " + visitId);
			}
		}
	}

	@Override
	public String execute() throws Exception {
		visitScheduleDao.delete(visitSchedule);
		if(existingVisit != null){
			visitDao.delete(existingVisit);
		}
		addActionError(getText("pl.grabar.clinic.client.web.reception.visit.actions.delete.deleted", new String[] { visitSchedule.getPatient(), visitSchedule.getDoctor(), visitSchedule.getVisitDate().toString() }));
		LOG.error("Usinieto uzytkownika o podanym id: " + visitId );
		return SUCCESS;
	}

	/* AKCESORY */

	public String getVisitId() {
		return visitId;
	}

	public void setVisitId(String visitId) {
		this.visitId = visitId;
	}

	public void setVisitScheduleDao(Dao<VisitSchedule> visitScheduleDao) {
		this.visitScheduleDao = visitScheduleDao;
	}

	public void setVisitDao(Dao<Visit> visitDao) {
		this.visitDao = visitDao;
	}

}